package com.bridgeintelligent.tag.customer.looklike;

import cn.hutool.core.util.RandomUtil;
import com.bridgeintelligent.tag.constants.bulkload.FileLoadMqMsg;
import com.bridgeintelligent.tag.constants.bulkload.MQConfig;
import com.bridgeintelligent.tag.customer.mapper.CustomersMapper;
import com.bridgeintelligent.tag.customer.mapper.LookLikeExportMapper;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
@Slf4j
public class LookLikeExportServiceImpl implements ILookLikeExportService {

    private static final String ZERO_STATUS = "0";

    private static final String ONE_STATUS = "1";

    protected RocketMQTemplate rocketMQTemplate;

    private LookLikeExportMapper lookLikeExportMapper;

    private CustomersMapper customersMapper;

    private ObjectMapper objectMapper;

    private ILookLikeService lookLikeService;

    @Override
    public void addLookLikeExport(LookLikeExportSet set) {
        User user = TagSecurityHelper.currentUser();
        //保存导出配置信息
        LookLikeExportConfig config = set.getConfig();
        config.setId(IDGenerator.gen()).setDateTime(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_1));
        lookLikeExportMapper.addLookExportConfig(config);
        //set保存基本信息
        set.setLookConfigId(config.getId())
                .setId(IDGenerator.gen())
                .setDataDate(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_8))
                .setUserId(user.getUserId())
                .setUserName(user.getUsername())
                .setIsready(ZERO_STATUS)
                .setCreateTime(DateHelper.currentDateTime())
                .setUptTime(DateHelper.currentDateTime())
                .setFlag(ONE_STATUS);
        lookLikeExportMapper.addLookExportSet(set);

        //推送mq消息
        FileLoadMqMsg fileLoadMqMsg = new FileLoadMqMsg();
        fileLoadMqMsg.setId(set.getId());
        fileLoadMqMsg.setIndexId(config.getEsIndex());
        fileLoadMqMsg.setUniqueIdentify(set.getId()+"_"+ RandomUtil.randomString(5));
        Map param = new HashMap();
        param.put("id",set.getId());
        try {
            String msg = objectMapper.writeValueAsString(fileLoadMqMsg);
            rocketMQTemplate.convertAndSend(MQConfig.FILE_LOAD_TAG_TOPIC, msg);
            //推送成功
            param.put("isready", "1");
            param.put("uptTime",DateHelper.currentDateTime());
        } catch (Exception e) {
            log.error(set.getId()+"客群导出信息推送MQ失败",e);
            param.put("isready", "3");
            param.put("uptTime",DateHelper.currentDateTime());
            param.put("reason","客群导出信息推送MQ失败");
        }
        customersMapper.updateById(param);

        //增加操作记录
        lookLikeService.addOperation(OperationEnum.EXPORT.getCode(),set.getLookId());

    }

    @Override
    public boolean checkName(String exportName) {
        Integer count = lookLikeExportMapper.checkExportName(exportName);
        count = count == null ? 0 : count;
        if (count > 0){
            return true;
        }
        return false;
    }

    @Override
    public LookLikeExportSet findById(String id) {
        LookLikeExportSet lookExportSet = lookLikeExportMapper.findLookExportSet(id);
        if (lookExportSet != null && !StringUtils.isEmpty(lookExportSet.getLookConfigId())){
            LookLikeExportConfig lookExportConfig = lookLikeExportMapper.findLookExportConfig(lookExportSet.getLookConfigId());
            if (lookExportConfig != null){
                lookExportSet.setConfig(lookExportConfig);
            }
        }
        return lookExportSet;
    }

    @Override
    public boolean retry(String id) {

        boolean flag = false;
        Map<String,String> map = new HashMap();
        map.put("uptTime", DateHelper.currentDateTime());
        map.put("id",id);

        LookLikeExportSet lookExportSet = lookLikeExportMapper.findLookExportSet(id);
        if (lookExportSet != null && !StringUtils.isEmpty(lookExportSet.getLookConfigId())){
            LookLikeExportConfig lookExportConfig = lookLikeExportMapper.findLookExportConfig(lookExportSet.getLookConfigId());
            if (lookExportConfig != null){
                FileLoadMqMsg fileLoadMqMsg = new FileLoadMqMsg();
                fileLoadMqMsg.setId(id);
                fileLoadMqMsg.setIndexId(lookExportConfig.getEsIndex());
                fileLoadMqMsg.setUniqueIdentify(id+"_"+ RandomUtil.randomString(5));
                try {
                    String msg = objectMapper.writeValueAsString(fileLoadMqMsg);
                    rocketMQTemplate.convertAndSend(MQConfig.FILE_LOAD_TAG_TOPIC, msg);
                    //推送成功
                    map.put("isready", "1");
                    map.put("reason","-");
                    flag = true;
                } catch (JsonProcessingException e) {
                    log.error(id+"lookLike导出信息推送MQ失败"+e);
                    map.put("isready", "3");
                    map.put("reason","lookLike导出信息推送MQ失败");
                }
                customersMapper.updateById(map);
            }
        }
        return flag;

    }

}
